import { useAppSelector, useAppDispatch, getArticleInfoAsync, getCommentListAsync } from '@/store/index'
import { useNavigate, useParams } from 'react-router-dom'
import { useInitialState } from '@/hooks/useInitialState'
import styles from './index.module.scss'
import Icon from '@/components/icon/index'
import CommentItem from './components/CommentItem/index'
import CommentFooter from './components/CommentFooter/index'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import classNames from 'classnames'
import dayjs from '@/plugin/dayjs/index.ts'
import DOMPurify from 'dompurify'
import hljs from '@/plugin/highlightjs/index'
import { useEffect, useRef, useState } from 'react'
import NoComment from './components/NoComment'

function Article() {
  const navigate = useNavigate()
  const params = useParams<{ id: string }>()
  const dispatch = useAppDispatch()
  // 获取文章信息
  const { articleInfo } = useInitialState(getArticleInfoAsync, 'articleSlice', params.id)

  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      ignoreUnescapedHTML: true //忽略未经转移的HTML字符
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('.dg-html')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [articleInfo])

  const wrapRef = useRef<HTMLDivElement>(null)
  const authorRef = useRef<HTMLDivElement>(null)
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  useEffect(() => {
    const wrapDom = wrapRef.current!
    const authDom = authorRef.current!
    function onScroll() {
      const rect = authDom.getBoundingClientRect()
      setIsShowAuthor(rect.top <= 0)
    }
    wrapDom.addEventListener('scroll', onScroll)
    return () => {
      wrapDom.removeEventListener('scroll', onScroll)
    }
  }, [])
  const {
    comment: { results: commentResult, last_id, end_id }
  } = useAppSelector((state) => state.articleSlice)

  const hasMore = !last_id || last_id !== end_id
  async function loadMore() {
    await dispatch(getCommentListAsync({ type: 'a', source: params.id as string, offset: last_id }))
  }
  //监听底部操作
  function footerFinish() {
    dispatch(getArticleInfoAsync(params.id as string))
  }
  function renderArticle() {
    // 文章详情
    return (
      <div className="wrapper" ref={wrapRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{articleInfo.title}</h1>

            <div className="info">
              <span>{dayjs(articleInfo.pubdate).format('YYYY-MM-DD')}</span>
              <span>{articleInfo.read_count} 阅读</span>
              <span>{articleInfo.comm_count} 评论</span>
            </div>

            <div className="author" ref={authorRef}>
              <img src="http://geek.itheima.net/images/user_head.jpg" alt="" />
              <span className="name">{articleInfo.aut_name}</span>
              <span className={classNames('follow', articleInfo.is_followed ? 'followed' : '')}>
                {articleInfo.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(articleInfo.content || '') }}
            />
            <div className="date">发布文章时间：{dayjs(articleInfo.pubdate).format('YYYY-MM-DD')}</div>
          </div>
        </div>

        <div className="comment">
          <div className="comment-header">
            <span>全部评论（{articleInfo.comm_count}）</span>
            <span>{articleInfo.like_count} 点赞</span>
          </div>

          <div className="comment-list">
            {articleInfo.comm_count === 0 ? (
              <NoComment></NoComment>
            ) : (
              commentResult?.map((item) => <CommentItem key={item.com_id} type="normal" comment={item} />)
            )}
            <InfiniteScroll hasMore={hasMore} loadMore={loadMore} />
          </div>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className={styles.root}>
        <div className="root-wrapper">
          <NavBar
            onBack={() => navigate(-1)}
            right={
              <span>
                <Icon type="icongengduo" />
              </span>
            }
          >
            {isShowAuthor && (
              <div className="nav-author">
                <img src={articleInfo.aut_photo} alt="" />
                <span className="name">{articleInfo.aut_name}</span>
                <span className={classNames('follow', articleInfo.is_followed ? 'followed' : '')}>
                  {articleInfo.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            )}
          </NavBar>
          {/* 文章详情和评论 */}
          {renderArticle()}

          {/* 底部评论栏 */}
          <CommentFooter articleInfo={articleInfo} operateFinish={footerFinish} />
        </div>
      </div>
    </>
  )
}
export default Article
